import { useState, useEffect, useRef } from 'react'
import { getTemplateListRequest, addRequest } from './ajax'
import { Modal, Form, Select, FormInstance, message } from 'antd';
import { awaitWrap } from '@src/assets/js/tool'
import { DocumentTemplateSchema } from '@src/components/schema/document'
import Upload, { uploadFile } from '@components/upload'

const { Item } = Form
const { Option } = Select

async function getTemplateList (setTemplateList: (v: DocumentTemplateSchema[]) => void) {
  const [e, d] = await awaitWrap(getTemplateListRequest())
  if (e === null && d !== null) {
    setTemplateList(d.list)
  }
}

async function submitHandle (data: { [k: string]: any }, caseid: string, refreshFn: () => void) {
  data.caseid = caseid
  data.user_define = 1
  const h = message.loading('提交中', 120)
  if (data.file instanceof Array && data.file.length > 0) {
    const files = await uploadFile(data.file)
    data.user_uploadid = files.map(li => li.id).join()
    data.filename = files.map(li => li.original_filename).join()
    delete data.file
  }
  const [e] = await awaitWrap(addRequest(data))
  h()
  if (e === null) {
    refreshFn()
  }
}

interface Props {
  visible: boolean
  hide: () => void
  caseid: string
  refreshFn: () => void
}

function Main ({ visible, hide, caseid, refreshFn }: Props) {
  const formRef = useRef<FormInstance>(null)
  const [templateList, setTemplateList] = useState<DocumentTemplateSchema[]>([])
  const [t, setT] = useState('文书模板')
  useEffect(() => {
    getTemplateList(setTemplateList)
  }, [])
  useEffect(() => {
    const c = formRef.current
    if (!visible && c) {
      c.resetFields()
      setT('文书模板')
    }
  }, [visible])
  return (
    <div>
      <Modal visible={visible} onCancel={() => hide()} maskClosable={false} title='新增文书' onOk={() => formRef.current?.submit()}>
        <Form ref={formRef} labelCol={{flex: '88px'}} onFinish={(d) => submitHandle(d, caseid, refreshFn)}>
          <Item label='文书来源' required>
            <Select placeholder='请选择' value={t} onChange={v => setT(v)}>
              <Option value='文书模板'>文书模板</Option>
              <Option value='文件上传'>文件上传</Option>
            </Select>
          </Item>
          {
            t === '文书模板' ? (
              <Item label='文书模板' name='filecode' rules={[{required: true, message: '文书模板不能为空'}]}>
                <Select placeholder='请选择'>
                  {templateList.map(li => {
                    return <Option key={li.id} value={li.code}>{li.title}</Option>
                  })}
                </Select>
              </Item>
            ) : (
              <Item label='文件' name='file' rules={[{required: true, message: '文件不能为空'}]}>
                <Upload accept='.docx,.pdf' maxLength={1} />
              </Item>
            )
          }
        </Form>
      </Modal>
    </div>
  )
}

export default Main
